package wildcard.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import wildcard.database.DBAccess;

public class OrderRecordExecuteServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// 実行結果
		ArrayList<ArrayList<String>> resultSelect; // 更新後の出力レコード
		int countInsert = 0;
		String errorString = "";

		// SQL用パラメータ
		ArrayList<String> selectParameters = new ArrayList<String>();
		ArrayList<String> insertParameters = new ArrayList<String>();

		// HTTPの設定
		req.setCharacterEncoding("UTF-8");
		HttpSession session = req.getSession();

		// ユーザIDの取得
		LoginBean loginBean = (LoginBean) session.getAttribute("LoginUser");
		String dbId = loginBean.getLoginId().substring(0, 2);
		String dbPassword = loginBean.getPassword();

		// SQL文を取得するためにデータベースにアクセスする
		String sqlId = req.getParameter("sql");
		selectParameters = new ArrayList<String>();
		selectParameters.add(sqlId);
		resultSelect = DBAccess.executeSelect(dbId, dbPassword,
				DBAccess.SQL_SELECT_COMMAND, selectParameters);

		// アクセスした結果を格納する
		String sql = resultSelect.get(1).get(0);

		System.out.println(this.getClass() + " : "
				+ req.getParameterValues("sql"));

		try {
			String[] idInputs = req.getParameterValues("menuId");
			String tableId = req.getParameter("tableId");

			for (String id : idInputs) {
				// quantity+ID(例quantity2)の名前があるテキストボックスの値を取得する。
				int quantity = Integer.parseInt(req.getParameter("quantity"
						+ id));

				for (int i = 0; i < quantity; i++) {
					insertParameters.removeAll(insertParameters);
					insertParameters.add(tableId);
					insertParameters.add(id);

					// 追加処理
					if (DBAccess.executeUpdate(dbId, dbPassword, sql,
							insertParameters) == 0) {
						errorString = "sql error!! : " + sql;
					} else {
						countInsert++;
					}

				}

			}
		} catch (NullPointerException nullpo) {
			System.out.println("ｶﾞｯ");
		}

		// 元の画面へ遷移
		RequestDispatcher dispatcher;
		req.setAttribute("result", String.valueOf(countInsert));
		req.setAttribute("error", errorString);
		dispatcher = req.getRequestDispatcher("android_main.jsp");

		dispatcher.forward(req, resp);
	}
}
